﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using QTMusic.BaseClasses;

namespace QTMusic.Websites
{
    public partial class Playing : System.Web.UI.Page
    {
        protected string songPath, songPathDownload, songName, genreName, artistName, likeCount, viewCount, uperName, songTimeUp, strUperId;
        int numberComment = 0;
        int numberLike = 0;
        int id;
        DataTable dt = new DataTable();
        string connectionString = Common.connString;
        

        protected void Page_Load(object sender, EventArgs e)
        {
            string  songId;
            string  selectSongPath, selectComment;
            string  songPathTemp;
            int genreId, artistId, uperId;

            songId = Request.QueryString["SongID"];
            if (songId != null)
            {
                id = int.Parse(songId);
                SqlDataReader sqlDataReader;
                SqlConnection sqlConnect = new SqlConnection(connectionString);
                sqlConnect.Open();

                // Lay id nguoi dang
                string selectUserUpload = "SELECT user_id FROM [songup] WHERE song_id = @songId";
                SqlCommand cmdSelectUserUpload = new SqlCommand(selectUserUpload, sqlConnect);
                cmdSelectUserUpload.Parameters.AddWithValue("@songId", id);
                SqlDataReader sqlDataUserUploadReader = cmdSelectUserUpload.ExecuteReader();
                sqlDataUserUploadReader.Read();
                uperId = (int)sqlDataUserUploadReader["user_id"];
                sqlDataUserUploadReader.Close();

                strUperId = uperId.ToString();
                // Lay thong tin be bai hat
                selectSongPath = "SELECT song_permission, song_play_count, song_name, artist_id, genre_id, song_path, song_description, song_like_count FROM [song] WHERE song_id = @songId";
                SqlCommand sqlCommand = new SqlCommand(selectSongPath, sqlConnect);
                sqlCommand.Parameters.AddWithValue("@songId", id);
                sqlDataReader = sqlCommand.ExecuteReader();
                sqlDataReader.Read();

                // kiem tra permission
                bool isAccept = false;
                HttpCookie userCookie = Request.Cookies["QTCookie"];
                if ((int)sqlDataReader["song_permission"] == (int)Common.Permission.Public)
                {
                    isAccept = true;
                }
                else 
                {
                    if ((int)sqlDataReader["song_permission"] == (int)Common.Permission.Friend)
                    {
                        if (userCookie != null)
                        {
                            if (Common.IsFriend(int.Parse(userCookie["ID"]), uperId))
                                isAccept = true;
                        }
                    }
                    else
                    {
                        if (userCookie != null)
                        {
                            if (int.Parse(userCookie["ID"]) == uperId)
                                isAccept = true;
                        }
                    }
                    sqlDataUserUploadReader.Close();
                }

                if (!isAccept)
                {
                    sqlDataReader.Close();
                    songPath = null;
                    sqlConnect.Close();
                    StatusLabel.Text = "Bạn hát này chỉ được chia sẻ cho bạn bè hoặc cá nhân người đăng";
                }
                else
                {
                    StatusLabel.Text = null;
                    songPathTemp = (string)sqlDataReader["song_path"];
                    songPath = "..\\MusicStorage\\" + songPathTemp;
                    songPathDownload = "MusicStorage\\" + songPathTemp;

                    if (sqlDataReader["song_description"] != DBNull.Value)
                        DescriptionTextBox.Text = (string)sqlDataReader["song_description"];

                    numberLike = (int)sqlDataReader["song_like_count"];
                    likeCount = numberLike.ToString();
                    int viewTemp = (int)sqlDataReader["song_play_count"];
                    if (!IsPostBack) ++viewTemp;
                    viewCount = viewTemp.ToString();
                    songName = (string)sqlDataReader["song_name"];
                    genreId = (int)sqlDataReader["genre_id"];
                    artistId = (int)sqlDataReader["artist_id"];
                    sqlDataReader.Close();

                    // Lay ten nguoi trinh bay
                    string selectArtistName = "SELECT artist_name FROM [artist] WHERE artist_id = @artistId";
                    SqlCommand cmdSelectArtist = new SqlCommand(selectArtistName, sqlConnect);
                    cmdSelectArtist.Parameters.AddWithValue("@artistId", artistId);
                    SqlDataReader sqlDataArtistReader = cmdSelectArtist.ExecuteReader();
                    if (sqlDataArtistReader != null)
                    {
                        sqlDataArtistReader.Read();
                        artistName = (string)sqlDataArtistReader["artist_name"];
                    }
                    sqlDataArtistReader.Close();

                    // Lay the loai cua bai hat
                    string selectGenreName = "SELECT genre_name FROM [genre] WHERE genre_id = @genreId";
                    SqlCommand cmdSelectGenre = new SqlCommand(selectGenreName, sqlConnect);
                    cmdSelectGenre.Parameters.AddWithValue("@genreId", genreId);
                    SqlDataReader sqlDataGenreReader = cmdSelectGenre.ExecuteReader();
                    if (sqlDataGenreReader != null)
                    {
                        sqlDataGenreReader.Read();
                        genreName = (string)sqlDataGenreReader["genre_name"];
                    }
                    sqlDataGenreReader.Close();

                    // Lay thong tin nguoi dang
                    string selectSongup = "SELECT user_name, songup_time FROM [songup], [user] WHERE [songup].user_id = [user].user_id AND [songup].song_id = @songId";
                    SqlCommand cmdSelectSongup = new SqlCommand(selectSongup, sqlConnect);
                    cmdSelectSongup.Parameters.AddWithValue("@songId", id);
                    SqlDataReader sqlDataSongupReader = cmdSelectSongup.ExecuteReader();
                    if (sqlDataSongupReader != null)
                    {
                        sqlDataSongupReader.Read();
                        songTimeUp = (string)sqlDataSongupReader["songup_time"].ToString();
                        uperName = (string)sqlDataSongupReader["user_name"];
                    }
                    sqlDataSongupReader.Close();

                    // Lay comment cua bai hat
                    selectComment = "SELECT songcmt_text, songcmt_time, user_name, [user].user_id, user_pic FROM [songcmt], [user] WHERE [songcmt].user_id = [user].user_id AND [songcmt].song_id = @songId";
                    SqlCommand cmdSelectComment = new SqlCommand(selectComment, sqlConnect);
                    cmdSelectComment.Parameters.AddWithValue("@songId", id);
                    SqlDataReader sqlDataCommentReader = cmdSelectComment.ExecuteReader();

                    dt.Columns.Add("UserName");
                    dt.Columns.Add("Comment");
                    dt.Columns.Add("Time");
                    dt.Columns.Add("UserId");
                    dt.Columns.Add("UserPic");

                    while (sqlDataCommentReader.Read())
                    {
                        DataRow newRow = dt.NewRow();

                        newRow["UserName"] = (string)sqlDataCommentReader["user_name"];
                        newRow["Comment"] = (string)sqlDataCommentReader["songcmt_text"];
                        newRow["Time"] = (string)sqlDataCommentReader["songcmt_time"].ToString();
                        newRow["UserId"] = ((int)sqlDataCommentReader["user_id"]).ToString();
                        newRow["UserPic"] = (string)sqlDataCommentReader["user_pic"];
                        dt.Rows.Add(newRow);
                        ++numberComment;
                    }

                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                    sqlDataCommentReader.Close();

                    // Thay doi so luot nghe bai hat
                    if (!IsPostBack)
                    {
                        string updatePlayCount = "UPDATE [song] SET song_play_count = song_play_count + 1 WHERE song_id = @songId";
                        SqlCommand cmdUpdatePlayCount = new SqlCommand(updatePlayCount, sqlConnect);
                        cmdUpdatePlayCount.Parameters.AddWithValue("@songId", id);
                        cmdUpdatePlayCount.ExecuteNonQuery();
                    }


                    // Kiem tra bai nay da dc like chua
                    if (userCookie != null)
                    {
                        string selectLikeActivity = "SELECT song_like_id FROM [activity] where user_id = @userId";
                        SqlCommand cmdSelectLikeActivity = new SqlCommand(selectLikeActivity, sqlConnect);
                        cmdSelectLikeActivity.Parameters.AddWithValue("@userId", int.Parse((string)userCookie["ID"]));
                        SqlDataReader sqlDataLikeActReader = cmdSelectLikeActivity.ExecuteReader();

                        bool isFound = false;
                        while (sqlDataLikeActReader.Read())
                        {
                            if (songId == sqlDataLikeActReader["song_like_id"].ToString())
                            {
                                isFound = true;
                                break;
                            }
                        }
                        sqlDataLikeActReader.Close();

                        if (isFound) LikeBtn.Text = "Không thích";
                        else LikeBtn.Text = "Thích";

                    }
                    sqlConnect.Close();
                    this.DataBind();
                }
            }
            LabelComment.Text = "Comment (" + numberComment.ToString() + ")      Like(" + numberLike.ToString() + ")";
        }

        protected void CommentBtn_Click(object sender, EventArgs e)
        {
            if (CommentTextboxt.Text != null)
            {
                string szInsertComment, userId;

                //Lay username
                HttpCookie userCookie = Request.Cookies["QTCookie"];

                if (userCookie != null)
                {
                    ++numberComment;
                    DataRow newRow = dt.NewRow();
                    newRow["UserName"] = userCookie["Name"];
                    newRow["Comment"] = CommentTextboxt.Text;
                    newRow["Time"] = System.DateTime.Now.ToShortDateString() + " " + System.DateTime.Now.ToLongTimeString();
                    dt.Rows.Add(newRow);

                    GridView1.DataSource = dt;
                    GridView1.DataBind();

                    SqlConnection sqlConnect = new SqlConnection(connectionString);
                    sqlConnect.Open();
                    userId = userCookie["ID"];

                    szInsertComment = "INSERT INTO songcmt(song_id, user_id, songcmt_time, songcmt_text) VALUES(@songId, @userId, @time, @text)";
                    SqlCommand cmdInsertComment = new SqlCommand(szInsertComment, sqlConnect);

                    cmdInsertComment.Parameters.AddWithValue("@songId", id);
                    cmdInsertComment.Parameters.AddWithValue("@userId", userId);
                    cmdInsertComment.Parameters.AddWithValue("@time", newRow["Time"]);
                    cmdInsertComment.Parameters.AddWithValue("@text", CommentTextboxt.Text);
                    cmdInsertComment.ExecuteNonQuery();

                    sqlConnect.Close();
                    StatusLabel.Text = "";
                    LabelComment.Text = "Comment (" + numberComment.ToString() + ")      Like(" + numberLike.ToString() + ")";
                }

                else
                {
                    StatusLabel.Text = "Bạn cần đăng nhập để sử dụng tính năng này";
                }
                CommentTextboxt.Text = "";
            }
        }

        protected void DownloadBtn_Click(object sender, EventArgs e)
        {
            // The file path to download.
            string filepath = Request.PhysicalApplicationPath + songPathDownload;
            // The file name used to save the file to the client's system..
            string filename = System.IO.Path.GetFileName(filepath);
            System.IO.Stream stream = null;
            try
            {
                // Open the file into a stream. 
                stream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
                // Total bytes to read: 
                long bytesToRead = stream.Length;
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                // Read the bytes from the stream in small portions. 
                while (bytesToRead > 0)
                {
                    // Make sure the client is still connected. 
                    if (Response.IsClientConnected)
                    {
                        // Read the data into the buffer and write into the 
                        // output stream. 
                        byte[] buffer = new Byte[10000];
                        int length = stream.Read(buffer, 0, 10000);
                        Response.OutputStream.Write(buffer, 0, length);
                        Response.Flush();
                        // We have already read some bytes.. need to read 
                        // only the remaining. 
                        bytesToRead = bytesToRead - length;
                    }
                    else
                    {
                        // Get out of the loop, if user is not connected anymore.. 
                        bytesToRead = -1;
                    }
                }

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                // An error occurred.. 
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }

            SqlConnection sqlConnect = new SqlConnection(connectionString);
            sqlConnect.Open();

            string updateDownloadCount = "UPDATE [song] SET song_download_count = song_download_count + 1 WHERE song_id = @songId";
            SqlCommand cmdUpdateDownloadCount = new SqlCommand(updateDownloadCount, sqlConnect);
            cmdUpdateDownloadCount.Parameters.AddWithValue("@songId", id);
            cmdUpdateDownloadCount.ExecuteNonQuery();

            sqlConnect.Close();
        }

        protected void LikeBtn_Click(object sender, EventArgs e)
        {
            HttpCookie userCookie = Request.Cookies["QTCookie"];
            if (userCookie != null)
            {
                if (LikeBtn.Text == "Thích")
                {
                    ++numberLike;
                    LikeBtn.Text = "Không thích";

                    SqlConnection sqlConnect = new SqlConnection(connectionString);
                    sqlConnect.Open();

                    string updateLikeCount = "UPDATE [song] SET song_like_count = song_like_count + 1 WHERE song_id = @songId";
                    SqlCommand cmdUpdateLikeCount = new SqlCommand(updateLikeCount, sqlConnect);
                    cmdUpdateLikeCount.Parameters.AddWithValue("@songId", id);
                    cmdUpdateLikeCount.ExecuteNonQuery();

                    string insertLikeActivity = "INSERT INTO activity(user_id, song_like_id, time) VALUES(@userId, @songId, @timeLike)";
                    SqlCommand cmdInsertLikeActivity = new SqlCommand(insertLikeActivity, sqlConnect);
                    cmdInsertLikeActivity.Parameters.AddWithValue("@songId", id);
                    cmdInsertLikeActivity.Parameters.AddWithValue("@userId", int.Parse((string)userCookie["ID"]));
                    cmdInsertLikeActivity.Parameters.AddWithValue("@timeLike", System.DateTime.Now.ToShortDateString() + " " + System.DateTime.Now.ToLongTimeString());
                    cmdInsertLikeActivity.ExecuteNonQuery();

                    sqlConnect.Close();
                    StatusLabel.Text = "";

                }
                else
                {
                    --numberLike;
                    LikeBtn.Text = "Thích";

                    SqlConnection sqlConnect = new SqlConnection(connectionString);
                    sqlConnect.Open();

                    string updateLikeCount = "UPDATE [song] SET song_like_count = song_like_count - 1 WHERE song_id = @songId";
                    SqlCommand cmdUpdateLikeCount = new SqlCommand(updateLikeCount, sqlConnect);
                    cmdUpdateLikeCount.Parameters.AddWithValue("@songId", id);
                    cmdUpdateLikeCount.ExecuteNonQuery();


                    string deleteLikeActivity = "DELETE FROM [activity] WHERE user_id = @userId AND song_like_id = @songId";
                    SqlCommand cmdDeleteLikeActivity = new SqlCommand(deleteLikeActivity, sqlConnect);
                    cmdDeleteLikeActivity.Parameters.AddWithValue("@songId", id);
                    cmdDeleteLikeActivity.Parameters.AddWithValue("@userId", int.Parse((string)userCookie["ID"]));
                    cmdDeleteLikeActivity.ExecuteNonQuery();

                    sqlConnect.Close();
                    StatusLabel.Text = "";
                }
            }
            else
            {
                StatusLabel.Text = "Bạn cần đăng nhập để sử dụng tính năng này";
            }
            LabelComment.Text = "Comment (" + numberComment.ToString() + ")      Like(" + numberLike.ToString() + ")";
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

        protected void ShareBtn_Click(object sender, EventArgs e)
        {
            HttpCookie userCookie = Request.Cookies["QTCookie"];
            if (userCookie != null)
            {
                string redirectLink = "Profile.aspx?id=" + userCookie["ID"] + "&SongId=" + id.ToString();
                Response.Redirect(redirectLink);
            }
            else
            {
                StatusLabel.Text = "Bạn cần đăng nhập để sử dụng tính năng này";
            }
        }

    }
}